import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/dao/package_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/login/suc_return_enum.dart';
import 'package:hktk_app/model/package/order_model.dart';
import 'package:hktk_app/model/package/package_model.dart';
import 'package:hktk_app/pages/package/order_payment_page.dart';
import 'package:hktk_app/util/buy_ios_util.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/package/package_card_widget.dart';
import 'package:hktk_app/widget/show_label_widget.dart';

class BuyDialog extends StatefulWidget {
  final PackageModel package;

  /// 当前卡片对应下标
  final int index;

  /// 是否隐藏支付方式（微信/支付宝）,true：隐藏，false：不隐藏
  final bool payHide;

  // 这里暂时隐藏立即支付。避免上架应用宝审核失败。等待审核完成才能进行微信支付
  /// 是否显示联系客服，true：联系客服，false：立即支付。默认为false。
  final bool server;

  BuyDialog({
    Key? key,
    required this.package,
    required this.index,
    this.payHide = false,
    this.server = false,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => _createBuyDialogState();
}

class _createBuyDialogState extends State<BuyDialog> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 总金额
  late double _totalMoney;

  /// 显示金额
  late double _showMoney;

  /// 套餐相关科目信息
  late List<SkuModel> _skuList;

  @override
  void initState() {
    super.initState();

    _totalMoney = 0;
    _showMoney = 0;
    _skuList = [];
    _futureInit = () async {
      Map<String, dynamic> map = {};
      try {
        if (widget.package.skuModels == null) {
          _skuList = await PackageDao.packageSkuList(
            packageId: widget.package.id!,
          );
        } else {
          _skuList = widget.package.skuModels!;
          for (SkuModel sku in _skuList) {
            if (sku.isSelect) {
              int price = sku.discountPrice ?? 0;
              double price2 = price / 100;
              _totalMoney = _totalMoney + price2;
              if (widget.payHide) {
                _showMoney = BuyIOSUtil.getIosPrice(_totalMoney);
                break;
              }
            }
          }
          if (!widget.payHide) {
            _showMoney = _totalMoney;
          }
        }
        map["success"] = true;
      } catch (e) {
        map = {"success": false, "msg": "未知错误，请重试"};
        if (e is DaoException) {
          map["msg"] = e.msg;
        }
      }
      return map;
    }();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    // 获取底部安全边距
    double bottom = ScreenUtil().bottomBarHeight;
    return Container(
      padding: EdgeInsets.only(top: 30, bottom: bottom),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24),
          topRight: Radius.circular(24),
        ),
      ),
      child: FutureBuilder<Map<String, dynamic>>(
        future: _futureInit,
        builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
        ) {
          if (snapshot.connectionState == ConnectionState.done) {
            Map<String, dynamic> map = snapshot.data!;
            if (!map["success"]) {
              WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                ToastUtil.show(context: _context, msg: map["msg"]);
              });
            }
            return Column(
              children: [
                Container(
                  padding: EdgeInsets.fromLTRB(30, 0, 30, 30),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                    color: colorBlack4,
                    width: 2,
                  ))),
                  child: PackageCardWidget(
                    isBuy: false,
                    package: widget.package,
                    index: widget.index,
                    payHide: widget.payHide,
                  ),
                ),
                Expanded(
                  child: ListView(
                    children: [
                      _selectedChapter(),
                      _addChapter(),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(vertical: 15, horizontal: 16),
                  decoration: const BoxDecoration(
                      color: colorWhite1,
                      boxShadow: [
                        BoxShadow(color: colorBlack4, offset: Offset(0, -1))
                      ]),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      SizedBox(
                        height: 47,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          // textBaseline: TextBaseline.alphabetic,
                          children: [
                            Text(
                              "合计：",
                              style: FontUtil.fontBlack1(20),
                            ),
                            Container(
                              padding: EdgeInsets.only(bottom: 4),
                              child: Icon(
                                Icons.currency_yen,
                                size: 22,
                                color: colorOrange6,
                              ),
                            ),
                            Text(
                              _showMoney.toStringAsFixed(2),
                              style: FontUtil.fontOrange6(28),
                            )
                          ],
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          if (widget.server) {
                            // 联系客服，弹框提示
                            ToastUtil.showDialogBox(
                              context: _context,
                              contentText: "请联系客服开通对应科目",
                              btnLeftShow: false,
                            );
                          } else {
                            // 判断是否是游客登录
                            if (visitorMode()) {
                              showDialog(context: _context, builder: (BuildContext context1){
                                return AlertDialog(
                                  title: Text("提示"),
                                  content: Text("请先登录"),
                                  actions: [
                                    TextButton(
                                      onPressed: () {
                                        Navigator.pop(context1);
                                      },
                                      child: Text("取消"),
                                    ),
                                    TextButton(
                                      onPressed: () {
                                        Navigator.pop(context1);
                                        Navigator.pushNamedAndRemoveUntil(_context,"/login", (route) => false);
                                      },
                                      child: Text("确定"),
                                    )
                                  ]
                                );
                              });
                              return;
                            }


                            // 立即支付
                            List<SkuModel> list = [];
                            List<String> list2 = [];
                            for (SkuModel sku in _skuList) {
                              if (sku.isSelect) {
                                list.add(sku);
                                list2.add(sku.id!);
                              }
                            }
                            if (list.isNotEmpty) {
                              if (dataUtilComm.dataModel.visitorsType) {
                                // 跳转登录页面
                                Navigator.pushNamed(_context, "/login",
                                    arguments: {
                                      "closeVisitors": false,
                                      "sucReturn": SucReturnEnum.ret,
                                    }).then((value) {
                                  if (value == true) {
                                    _createOrderFun(list: list, list2: list2);
                                  }
                                });
                              } else {
                                _createOrderFun(list: list, list2: list2);
                              }
                            } else {
                              ToastUtil.show(
                                  context: _context, msg: "请至少选择一个科目！");
                            }
                            ;
                          }
                        },
                        child: Container(
                          // width: 172,
                          // height: 68,
                          padding:
                              EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                          decoration: BoxDecoration(
                              color: colorBlue1,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(44))),
                          child: Center(
                            child: Text(
                              widget.server ? "联系客服" : "立即支付",
                              style: FontUtil.fontWhile1(20,
                                  fontWeight: FontWeight.w500),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

  _createOrderFun({
    required List<SkuModel> list,
    required List<String> list2,
  }) {
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    // 创建订单
    PackageDao.createOrder(skuIds: list2).then((OrderModel orderModel) {
      ToastUtil.loadingBoxRemove();
      // 跳转对应页面
      Navigator.pushNamed(_context, "/order/pay", arguments: {
        "price": _totalMoney,
        "skuList": list,
        "package": widget.package,
        "index": widget.index,
        "orderModel": orderModel,
        "iosPrice": _showMoney,
        "payHide": widget.payHide,
      });
    }).catchError((e) {
      ToastUtil.loadingBoxRemove();

      String str = "未知错误，请重试";
      if (e is DaoException) {
        str = e.msg;
      }
      ToastUtil.show(context: _context, msg: str);
    });
  }

  /// 章节边框数据方法
  _chapterContainer(List<Widget> list) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 30, horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: list,
      ),
    );
  }

  _addChapter() {
    return _chapterContainer([
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "添加科目",
            style: FontUtil.fontBlack1(20, fontWeight: FontWeight.w500),
          )
        ],
      ),
      hiSpace(height: 20),
      () {
        List<Widget> list = [];
        for (int i = 0; i < _skuList.length; i++) {
          SkuModel sku = _skuList[i];
          list.add(GestureDetector(
            onTap: () {
              int price = sku.discountPrice ?? 0;
              double price2 = price / 100;
              if (sku.isSelect == false) {
                // 添加新科目
                if (widget.payHide) {
                  // 如果是iOS内购模式，则在有多个选项的时候只允许选择一个
                  for (SkuModel sku in _skuList) {
                    sku.isSelect = false;
                  }
                  _totalMoney = 0;
                }
                sku.isSelect = true;
                _totalMoney = _totalMoney + price2;
              } else {
                // 取消选择的科目，直接取消
                sku.isSelect = false;
                _totalMoney = _totalMoney - price2;
              }
              // 刷新
              setState(() {
                _skuList[i] = sku;
                if (widget.payHide) {
                  _showMoney = BuyIOSUtil.getIosPrice(_totalMoney);
                } else {
                  _showMoney = _totalMoney;
                }
              });
            },
            child: ShowLabelWidget(
              text: sku.name!,
              showIcon: sku.isSelect,
            ),
          ));
        }

        return Wrap(
          // 主轴方向子widget的间距
          spacing: 24,
          // 纵轴方向的间距
          runSpacing: 24,
          children: list,
        );
      }(),
    ]);
  }

  /// 已选科目
  _selectedChapter() {
    return _chapterContainer([
      Text(
        "已选科目",
        style: FontUtil.fontBlack1(20, fontWeight: FontWeight.w500),
      ),
      hiSpace(height: 20),
      () {
        List<Widget> list = [];
        for (int i = 0; i < _skuList.length; i++) {
          SkuModel sku = _skuList[i];
          if (sku.isSelect) {
            list.add(ShowLabelWidget.cancel(
              text: sku.name!,
              index: i,
              iconFun: (int i) {
                // 计算总价格
                int price = _skuList[i].discountPrice ?? 0;
                double price2 = price / 100;
                _totalMoney = _totalMoney - price2;
                // 刷新
                setState(() {
                  _skuList[i].isSelect = false;
                  if (widget.payHide) {
                    _showMoney = BuyIOSUtil.getIosPrice(_totalMoney);
                  } else {
                    _showMoney = _totalMoney;
                  }
                });
              },
            ));
          }
        }
        return Wrap(
          // 主轴方向子widget的间距
          spacing: 24,
          // 纵轴方向的间距
          runSpacing: 24,
          children: list,
        );
      }(),
    ]);
  }
}
